/*
 Peyote 3D 
 
 Copyright (c) 2010 Douglas J Lockamy
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */
#include <os_host.h>
#include <os_window.h>
#include <stdio.h>                                        

/* gl.h we need OpenGL :-) */
#include <GL/gl.h>           
/* this file is needed for X11 applications if we want to use hardware rendering */
#include <GL/glx.h>                                                                
#include <GL/glu.h>                                                                

#include <product.h>

#define WIDTH 640
#define HEIGHT 480
#define TITLE PRODUCT_NAME

extern int global_isRunning;
/*
typedef struct {
    Display *dpy;
    int screen;  
    Window win;  
    GLXContext ctx;
    XSetWindowAttributes attr;
    Bool fs;                  
    Bool doubleBuffered;      
    XF86VidModeModeInfo deskMode;
    int x, y;                    
    unsigned int width, height;  
    unsigned int depth;                                                                                                                                        
} GLWindow;                                                                                                                                                    
*/
GLWindow GLWin;                                                                                                                                                

/* most important variable
 * it contains information about the X server which we communicate with
 */                                                                    
Display               * display;                                       
int                     screen;                                        
/* our window instance */                                              
Window                  window;                                        
GLXContext              context;                                       
XSetWindowAttributes    winAttr;                                       
Bool                    fullscreen = False;                            
Bool                    doubleBuffered;                                
/* original desktop mode which we save so we can restore it later */   
XF86VidModeModeInfo     desktopMode;                                   
int                     x, y;                                          
unsigned int            width, height;                                 
unsigned int            depth;                                         

GLfloat                 rotQuad = 0.0f;

/* attributes for a single buffered visual in RGBA format with at least
 * 4 bits per color and a 16 bit depth buffer */                       
static int attrListSgl[] =                                             
{                                                                      
    GLX_RGBA, GLX_RED_SIZE, 4,                                         
    GLX_GREEN_SIZE, 4,                                                 
    GLX_BLUE_SIZE, 4,                                                  
    GLX_DEPTH_SIZE, 16,                                                
    None                                                               
};                                                                     

void resizeGL(unsigned int width, unsigned int height)
{                                                     
    /* prevent divide-by-zero */                      
    if (height == 0)                                  
        height = 1;                                   
    glViewport(0, 0, width, height);                  
    glMatrixMode(GL_PROJECTION);                      
    glLoadIdentity();                                 
    gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
    glMatrixMode(GL_MODELVIEW);                                           
} 

/* attributes for a double buffered visual in RGBA format with at least
 * 4 bits per color and a 16 bit depth buffer */                       
static int attrListDbl[] =                                             
{                                                                      
    GLX_RGBA, GLX_DOUBLEBUFFER,                                        
    GLX_RED_SIZE, 4,                                                   
    GLX_GREEN_SIZE, 4,                                                 
    GLX_BLUE_SIZE, 4,                                                  
    GLX_DEPTH_SIZE, 16,                                                
    None                                                               
};  

int os_window_init(int argc, char** argv)
{
	printf("os_window_init\n");
	
    XVisualInfo *vi;
    Colormap cmap;  
    int i, dpyWidth, dpyHeight;
    int glxMajor, glxMinor, vmMajor, vmMinor;
    XF86VidModeModeInfo **modes;             
    int modeNum, bestMode;                   
    Atom wmDelete;                           
    Window winDummy;                         
    unsigned int borderDummy;                
	
    /* set best mode to current */
    bestMode = 0;                 
    /* get a connection */        
    display = XOpenDisplay(0);    
    screen = DefaultScreen(display);
    //XF86VidModeQueryVersion(display, &vmMajor, &vmMinor);

    printf("XF86 VideoMode extension version %d.%d\n", vmMajor, vmMinor);
    XF86VidModeGetAllModeLines(display, screen, &modeNum, &modes); 
	
	printf(".....1..\n");
    /* save desktop-resolution before switching modes */                 
	//GLWin.deskMode = *modes[0];                                          
    /* look for mode with requested resolution */                        
    for (i = 0; i < modeNum; i++)                                        
    {                                                                    
        if ((modes[i]->hdisplay == width) && (modes[i]->vdisplay == height))
            bestMode = i;                                                   
    }                                                                       
    /* get an appropriate visual */                                         
    vi = glXChooseVisual(display, screen, attrListDbl);                     
	printf(".....2..\n");
    if (vi == NULL)                                                         
    {                                                                       
        vi = glXChooseVisual(display, screen, attrListSgl);                 
        doubleBuffered = False;                                             
        printf("singlebuffered rendering will be used, no doublebuffering available\n");
    }                                                                                   
    else                                                                                
    {                                                                                   
        doubleBuffered = True;                                                          
        printf("doublebuffered rendering available\n");                                 
    }
		printf(".....3..\n");
    glXQueryVersion(display, &glxMajor, &glxMinor);                                     
    printf("GLX-Version %d.%d\n", glxMajor, glxMinor);                                  
    /* create a GLX context */                                                          
    context = glXCreateContext(display, vi, 0, GL_TRUE);                                
    /* create a color map */                                                            
    cmap = XCreateColormap(display, RootWindow(display, vi->screen),                    
						   vi->visual, AllocNone);                                                         
    winAttr.colormap = cmap;                                                            
    winAttr.border_pixel = 0;                                                           
	
    if (fullscreen)
    {      
        printf("fullscreen");
        /* switch to fullscreen */
        XF86VidModeSwitchToMode(display, screen, modes[bestMode]);
        XF86VidModeSetViewPort(display, screen, 0, 0);            
        dpyWidth = modes[bestMode]->hdisplay;                     
        dpyHeight = modes[bestMode]->vdisplay;                    
        printf("resolution %dx%d\n", dpyWidth, dpyHeight);        
        XFree(modes);                                             
		
        /* set window attributes */
        winAttr.override_redirect = True;
        winAttr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
		StructureNotifyMask;                                            
        window = XCreateWindow(display, RootWindow(display, vi->screen),    
							   0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual,
							   CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,   
							   &winAttr);                                                       
        XWarpPointer(display, None, window, 0, 0, 0, 0, 0, 0);               
		XMapRaised(display, window);                                 
        XGrabKeyboard(display, window, True, GrabModeAsync,                  
					  GrabModeAsync, CurrentTime);                                     
        XGrabPointer(display, window, True, ButtonPressMask,                 
					 GrabModeAsync, GrabModeAsync, window, None, CurrentTime);        
    }                                                                        
    else                                                                     
    {      
		printf("windowed\n\n\n\n\n\n");
        /* create a window in window mode*/                                  
        winAttr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | 
		StructureNotifyMask;                                             
        window = XCreateWindow(display, RootWindow(display, vi->screen),     
							   0, 0, 640, 480, 0, vi->depth, InputOutput, vi->visual,      
							   CWBorderPixel | CWColormap | CWEventMask, &winAttr);    
		
        /* only set window title and handle wm_delete_events if in windowed mode */
        wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", True);                 
        XSetWMProtocols(display, window, &wmDelete, 1);                            
        XSetStandardProperties(display, window, TITLE,                             
							   TITLE, None, NULL, 0, NULL);                                           
        XMapRaised(display, window);  
    }
	
    /* connect the glx-context to the window */                                    
    glXMakeCurrent(display, window, context);                                      
    if (glXIsDirect(display, context))                                             
        printf("DRI enabled\n");                                                   
    else                                                                           
        printf("no DRI available\n"); 
	printf("init gl\n");

	return 0;
};


//window functions
int os_createWindow(const char *name,struct rect r,int flags)
{
	return -1;
};

int os_deleteWindow(int id)
{
	return -1;
};

int os_moveWindow(struct rect newRect)
{
	return -1;
};

int os_resizeWindow(struct rect newRect)
{
	return -1;
};

int done;
XEvent event;

int os_statInput(void)
{	
		//* handle the events in the queue 
        while (XPending(display) > 0)        
        {                                    
            XNextEvent(display, &event);     
            switch (event.type)              
            {                                
                case Expose:                 
					if (event.xexpose.count != 0)
						break;                                        
					break;                       
				case ConfigureNotify:            
                    // call resizeGL only if our window-size changed 
					if ((event.xconfigure.width != GLWin.width) ||
						(event.xconfigure.height != GLWin.height))
					{
						width = event.xconfigure.width;
						height = event.xconfigure.height;
						resizeGL(width, height);
					}
					break;
					//* exit in case of a mouse button press 
                case ButtonPress:
                        global_isRunning = 0;
                    break;
                case KeyPress:
					/*
                    if (XLookupKeysym(&event.xkey, 0) == XK_Escape)
                    {
                        global_isRunning = 0;
                    }
                    if (XLookupKeysym(&event.xkey,0) == XK_F1)
                    {
                        //destroyWindow();
                        fullscreen = !fullscreen;
                        //createWindow();
                    }*/
					//os_
                    break;
                case ClientMessage:
                    if (strcmp(XGetAtomName(display, event.xclient.message_type),
                               "WM_PROTOCOLS") == 0)
                    {
                        done = True;
                    }
                    break;
                default:
                    break;
            }
        }
	
	return -1;
	
};

int os_update(void)
{
	return -1;
};

void os_keyboard(unsigned char key, int x, int y)
{
	switch (key) {
		case 27:    /* ESC key */
		case 'Q':   /* Q|q keys */
		case 'q':
			exit(0);
			break;
		default:
			break;
	}	
};

void os_mouse(unsigned char key, int x, int y)
{
	
};

void os_touch(unsigned char key, int x, int y)
{
	
};

